package com.hua.demo.edu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hua.R;
import com.hua.demo.edu.entity.Chapter;
import com.hua.demo.edu.entity.Video;
import com.hua.demo.edu.entity.chapter.ChapterVo;
import com.hua.demo.edu.service.ChapterService;
import com.hua.demo.edu.service.VideoService;
import com.hua.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author huazi
 * @since 2021-11-24
 */
@RestController
@RequestMapping("/edu/chapter")
public class ChapterController {
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;
    @GetMapping("getchaptervideo/{courserid}")
    public R getchapervideo(@PathVariable String courserid){
        List<ChapterVo> list=chapterService.getchaptervideobycourseid(courserid);
        return R.ok().data("allchaptervideo",list);
    }
    @PostMapping("addchapter")
    public R addchapter(@RequestBody Chapter chapter){
        chapterService.save(chapter);
        return R.ok();
    }
    @PostMapping("updatechapter")
    public R updatechapter(@RequestBody Chapter chapter){
        boolean update = chapterService.updateById(chapter);
        if(update)
            return R.ok();
        else
            return R.error();

    }
    @DeleteMapping("deletechapter/{id}")
    public R delete(@PathVariable String id){
        Chapter chapter = chapterService.getById(id);
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("chapter_id",chapter.getId());
        int count = videoService.count(videoQueryWrapper);
        if(count>0){
           throw new GuliException(20001,"不可以删除");
            }
        else {
            boolean b = chapterService.removeById(id);
            if(b)
                return R.ok();
            else
                return R.error();
        }



    }
    @GetMapping("getchapterbyid/{id}")
    public R getchapterbyid(@PathVariable String id){
        Chapter byId = chapterService.getById(id);
        return R.ok().data("chapter",byId);
    }


}

